package org.example.springboot.common.aspect;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.springboot.common.annotation.CheckLogin;
import org.example.springboot.common.exception.CheckLoginException;
import org.example.springboot.common.exception.ServerException;
import org.example.springboot.entity.User;
import org.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Aspect
@Component
public class LoginCheckAspect {

    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 找到处理的切点
     * * *(..)  可以处理所有的方法
     */
    @Pointcut("@annotation(org.example.springboot.common.annotation.CheckLogin)")
    public void checkNetBehavior() {

    }

    /**
     * 处理切面
     */
    @Before("checkNetBehavior()")
    public void checkNet(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        CheckLogin auth = signature.getMethod().getAnnotation(CheckLogin.class);
        if (auth != null) {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            Optional.ofNullable(attributes).ifPresent(s -> {
                HttpServletRequest request = attributes.getRequest();
                String token = request.getHeader("token");
                if (StringUtils.isEmpty(token)) {
                    throw new ServerException("用户未登录");
                }
                String username = stringRedisTemplate.opsForValue().get(token);
                if (username == null) {
                    throw new ServerException("用户未登录");
                }
                User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
                if (user == null) {
                    throw new ServerException("用户不存在");
                }
            });
        }
    }

}
